package demo;

import java.io.*;
import java.net.*;

public class MultiClientServer implements Runnable {
    static int SeriaNum = 0;
    Socket socket;

    public MultiClientServer(Socket socket) {
        this.socket = socket;
    }

    public static void main(String[] args) {
        int MaxClientNum = 3;
        try {
            ServerSocket serverSocket = new ServerSocket(1680);
            for (int i = 1; i <= MaxClientNum; i++) {
                Socket socket = serverSocket.accept();
                Thread thread = new Thread(new MultiClientServer(socket));
                thread.start();
            }
            serverSocket.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void run() {
        int myNum = ++SeriaNum;

        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
            BufferedReader sin = new BufferedReader(new InputStreamReader(System.in));

            String s;
            while(!(s = in.readLine()).equals("bye")){
                System.out.println("# 第" + myNum + "个客户端信息:" + s);
                out.println(sin.readLine());
            }
            System.out.println("链接正在关闭");
            in.close();
            out.close();
            socket.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
